var express = require('express');
var router = express.Router();
var qiniu = require('qiniu');
var superagent = require('superagent');
var async = require( 'async'); // 同步控制
var moment = require('moment');  // 日期格式化


var SJGNode = require('./../../sjg/common/tg/SJGNode');
//var SJGTG = require('./../../sjg/common/tg/SJGTG');
//var SJGTGV3 = require('./../../sjg/common/tg3/SJGTGV3');
//var SJGNodeV3 = require('./../../sjg/common/tg3/SJGNodeV3');
var GlobalData = require('./../../sjg/z/GlobalData');
var SJGPage = require('./../../sjg/kernel/cont/SJGPage');
//var GroupObj = require('./../../sjg/kernel/obj/GroupObj');
//var TextExtObj = require('./../../sjg/kernel/obj/TextExtObj');
//var ImageObj = require('./../../sjg/kernel/obj/ImageObj');

var TgSearchTagModel = require('../../../common/mysql/mapping/TgSearchTagModel');
var ItbNotificationModel = require('../../../common/mysql/mapping/ItbNotificationModel');
var TgTypeModel = require('../../../common/mysql/mapping/TgTypeModel');
var TgSpecialTopicModel = require('../../../common/mysql/mapping/TgSpecialTopicModel');
var TgKeywordModel = require('../../../common/mysql/mapping/TgKeywordModel');
var TgOutlineModel = require('../../../common/mysql/mapping/TgOutlineModel');
var TgDesignDocModel = require('../../../common/mysql/mapping/TgDesignDocModel');
var TgUserDocModel = require('../../../common/mysql/mapping/TgUserDocModel');
var TgUserPageModel = require('../../../common/mysql/mapping/TgUserPageModel');
var TgUserPcModel = require('../../../common/mysql/mapping/TgUserPcModel');
var ItbUserModel = require('../../../common/mysql/mapping/ItbUserModel');
var CONFIG = require('../../../common/config');
var CODE = require('../../../common/code');
var BASE_IP = CONFIG.BASE_IP;

var ParserClassLoader = require('./../../sjg/kernel/base/ParserClassLoader');
ParserClassLoader.loadKernelClass();// 加载类加载器

var tgUtil = (function () {
    function tgUtil() {
    }

    //------------------------------------------------------------------
    // 返回json
    tgUtil.ret_func_json = function (success, msg, data, res){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    //------------------------------------------------------------------
    /* 调整图片尺寸，例如：删除印品的图片的出血区域
     * 参数：typeL: 0 未分类   1 海报  2 多页  3 ppt.  4. 印品 //  从5.x开始增加此参数，注意之前的接口没有此参数
     * 参数  docId: 文档id
     * 参数  isDesign: 1:    docId为[设计模版]文档id,
     *               0或空: docId为[用户作品]文档id
     * 参数  pageList:含有图片信息的数组，数组元素含有字段：thumb，表示图片地址
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          size: {  // 调整后的 模版或作品尺寸，注意：印品模版去除了出血
     *                   "w":720,
     *                   "h":1280
     *                 },
     * 注意：函数会直接修改pageList中国年的thumb
     */
    tgUtil.adjust_size_of_image = function (typeL, docId, isDesign, pageList,callback){
        // 获取尺寸
        tgUtil.get_size_of_doc (docId, isDesign, function(error, size){
            if(size){
                if(typeL==4 &&    size.bleed>0 && size.dpi>0 && size.ratio>0){
                    // 模版／作品的出血：
                    var temBleed = Math.ceil(size.bleed*size.dpi/25.4*size.ratio);
                    // 用OSS进行裁切，http://image-demo.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=image/crop,x_100,y_50,w_100,h_100
                    var newW = size.width-2*temBleed;
                    var newH = size.height-2*temBleed;
                    var suffix = '?x-oss-process=image/resize,w_'+size.width+'/crop,x_'+temBleed+',y_'+temBleed+',w_'+newW+',h_'+newH;

                    for(var i=0;i<pageList.length;i++){
                        var one = pageList[i];
                        one.thumb += suffix;
                    }
                    return callback(null, {w:newW,h:newH});
                }else{
                    return callback(null, {w:size.width,h:size.height});
                }
            }else{
                return callback(error,null);
            }
        });
    }

    //------------------------------------------------------------------
    /* 获取模版／作品的尺寸信息
     * 参数  docId: 文档id
     * 参数  isDesign: 1:    docId为[设计模版]文档id,
     *               0或空: docId为[用户作品]文档id
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          data:tg_size的model
     *
     */
    tgUtil.get_size_of_doc = function (docId, isDesign, callback){
        var pgEntity = null;
        if(isDesign) {
            pgEntity = new TgDesignDocModel({
                design_id: docId,
                del_flg:0
            });
        }else{
            pgEntity = new TgUserDocModel({
                doc_id: docId,
                del_flg:0
            });
        }
        pgEntity.findSizeInfo(function(error, size){
            if(error){
                return callback(error,null);
            }
            if(!size){
                return callback(null,null);
            }
            return callback(null,size);
        });
    }



    //------------------------------------------------------------------
    /* 获取切换模历史消息
     * 参数  getHis: 1表示获取历史消息
     * 参数  docId: 文档id
     * 参数  userId: 用户id
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          data:历史纪录
     */
    tgUtil.getSwitchHis = function (getHis, docId, userId, callback){
        if(1 == getHis){
            var url = CONFIG.SWITCH_SERVER_DOMAIN +':'+CONFIG.SWITCH_SERVER_PORT+'/tgSwitch/getHisList?'
                +'docId='+docId
                +'&userId='+userId;

            superagent.get(url)
                .end(function(err, res){
                    if(err){
                        console.log('tg.js [getDocPreviewEx] SuperAgent getHisList Err: ' + err);
                        return callback(err, null);
                    }

                    console.log('tg.js [getDocPreviewEx] SuperAgent getHisList:\n'+res.text);
                    var retJson = JSON.parse(res.text);
                    if(retJson.success){
                        return callback(null, retJson.data||[]);

                    } else {
                        return callback(retJson.msg, null);
                    }
                }
            );

        } else {
            return callback(null, null);
        }
    }

    //------------------------------------------------------------------
    /* 获取用户信息
     * 参数  user_id: 用户id
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          data:用户信息
     */
    tgUtil.getUserInfo = function (user_id, callback){
        if(!user_id){
            return callback(null, null);
        }
        var userEntity = new ItbUserModel({
            user_id:user_id
        });
        userEntity.findFromDB(function(error, items){
            if(error){
                return callback(error, null);
            }
            if(items.length==0){
                return callback(null, null);
            }
            return callback(null, items[0]);
        });
    }




    //------------------------------------------------------------------

    return tgUtil;
})();
//------------------------------------------------------------------
module.exports = tgUtil;

